package su.myteachprojects.javascriptlearn;

import com.oracle.truffle.js.scriptengine.GraalJSScriptEngine;
import org.graalvm.polyglot.Context;
import org.graalvm.polyglot.HostAccess;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;

@SpringBootApplication
public class JavascriptLearnApplication implements ApplicationRunner {

	public static void main(String[] args) {
		SpringApplication.run(JavascriptLearnApplication.class, args);
	}

	@Override
	public void run(ApplicationArguments args) throws Exception {

		ScriptEngine engine = GraalJSScriptEngine.create(null,
				Context.newBuilder("js")
						.allowExperimentalOptions(true)
						.option("js.syntax-extensions", "true")
						.allowHostAccess(HostAccess.ALL)
						.allowAllAccess(true)
						.allowIO(true)
						.allowHostClassLookup(s -> true)
		);

		Bindings bnd = engine.getBindings(ScriptContext.ENGINE_SCOPE);
		bnd.put("greeting", new Greeting());
		engine.eval("console.log('[js        ] Have a nice day all of you !!!')");
		engine.eval("greeting.printGreeting()");

	}

}
